<template>
  <QfPage title="报名管理">
    <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
      <template #bodyCell="{ record, column }">
        <!-- 判断如何是 key等于 action的时候 就按照下面的模板的内容来显示 -->
        <template v-if="column.key === 'action'">
          <a-button @click="handleEdit(record)">查看报名信息</a-button>
        </template>
      </template>
    </a-table>

    <!-- 分页的操作 -->
    <template #ft>
      <a-pagination
        v-model:current="page"
        :defaultPageSize="limit"
        :total="total"
        show-less-items
        @change="onPageChange"
      />
    </template>
  </QfPage>
</template>

<script>
import { defineComponent } from 'vue';
import _ from 'lodash';
import dayjs from 'dayjs';
import { message, Modal } from 'ant-design-vue';
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import EventApi from '@/api/event';
import { getBmList } from '@/api/bm';

export default defineComponent({
  data() {
    return {
      cusForm: [
        {
          label: '',
          placeholder: '',
          varname: '',
          type: '',
          options: [],
        },
      ],
      showEdit: false,
      page: 1,
      total: 0,
      limit: 5,
      eventName: '',
      locale,

      dataSource: [],
      columns: [
        {
          title: 'id', // 表头文字内容
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: 'uid',
          dataIndex: 'uid',
          key: 'uid',
        },
        {
          title: '赛事id',
          dataIndex: 'eventid',
          key: 'eventid',
        },

        {
          title: '报名时间',
          key: 'enrollRange',
          customRender({ record }) {
            const s = dayjs(record.createdAt).format('YYYY-MM-DD');
            return `${s}`;
          },
        },
        {
          title: '操作',
          key: 'action',
        },
      ],
      rangCount: '',
      showAddModal: false,
      curStep: 0,
      jfList: [], // 新增的时候的积分奖励列表
      eidtJfList: [], // 编辑的时候的积分奖励列表
      newEvent: {
        name: '',
        peopleLimit: '',
        desc: '',
        startMoney: '',
        enrollRange: [],
        eventRange: [],
      },
      editEvent: {
        name: '',
        peopleLimit: '',
        desc: '',
        startMoney: '',
        enrollRange: [],
        eventRange: [],
      },
      curId: null,
    };
  },
  created() {
    this.getData();
  },
  watch: {
    page(nv) {
      console.log('页码的值', nv);
    },
  },
  methods: {
    // 临时的查看自定义表单的规则
    showCusForm() {
      console.log('组定义表单', this.cusForm);
    },
    // 处理删除的操作
    async handleDel(id) {
      console.log('id', id);
      // 提醒用户进行删除的二次确认
      Modal.confirm({
        title: '删除赛事',
        content: '确定了？不后悔？一次机会都不给了？？？',
        onOk: async () => {
          const res = await EventApi.delEvent(id);
          console.log('删除的结果 ', res);
          const { status } = res;
          if (status !== 200) return message.warning('删除失败');
          message.success('删除成功');
          return this.getData();
        },
        onCancel() {
          console.log('Cancel');
        },
        class: 'test',
      });
    },
    // 处理分页页码变化
    onPageChange(page) {
      this.page = page;
      this.getData();
    },
    // 搜索 根据赛事名称
    onSearch() {
      this.page = 1;
      this.getData();
    },
    test() {
      console.log('校验的结果');
      this.$refs.addForm
        .validate()
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    async checkDate() {
      // 如果有了比赛时间和报名时间 比赛时间不能早于报名的截止时间
      const enrollEtime = this.newEvent.enrollRange[1];
      const eventStime = this.newEvent.eventRange[0];
      if (enrollEtime && eventStime) {
        if (enrollEtime.isAfter(eventStime)) {
          // 如果报名截止事件晚于比赛开始时间
          return Promise.reject('比赛时间不能早于报名的截止时间');
        }
      }
      return Promise.resolve();
    },
    async checkEditDate() {
      // 如果有了比赛时间和报名时间 比赛时间不能早于报名的截止时间
      const enrollEtime = this.editEvent.enrollRange[1];
      const eventStime = this.editEvent.eventRange[0];
      if (enrollEtime && eventStime) {
        if (enrollEtime.isAfter(eventStime)) {
          // 如果报名截止事件晚于比赛开始时间
          return Promise.reject('比赛时间不能早于报名的截止时间');
        }
      }
      return Promise.resolve();
    },
    checkMoney() {
      const { startMoney } = this.newEvent;
      if (startMoney < 100) {
        return Promise.reject('起始资金不能小于100');
      }
      return Promise.resolve();
    },
    checkEditMoney() {
      const { startMoney } = this.editEvent;
      if (startMoney < 100) {
        return Promise.reject('起始资金不能小于100');
      }
      return Promise.resolve();
    },
    // 执行修改
    async confirmUpdate() {
      this.$refs.editForm
        .validate()
        .then(async (result) => {
          // 表单校验成功
          // 第一个表单的数据
          const { enrollRange, eventRange, ...rest } = this.editEvent;
          const postData = {
            ...rest,
          };

          // 报名时间;
          const [enrollStime, enrollEtime] = this.editEvent.enrollRange;
          postData.enrollStime = enrollStime.$d;
          postData.enrollEtime = enrollEtime.$d;

          // 比赛时间
          const [sTime, eTime] = this.editEvent.eventRange;
          postData.stime = sTime.$d;
          postData.etime = eTime.$d;
          postData.jf = JSON.stringify(this.eidtJfList);

          // 开始可以执行ajax要求
          const res = await EventApi.editEvent(this.curId, postData);
          console.log('添加的结果是', res);
          const { status } = res;
          if (status !== 200) return message.warning('编辑失败');
          message.success('编辑成功');
          this.showEdit = false;
          this.getData();
          return false;
        })
        .catch((err) => {
          // 表单校验失败
          console.log('err', err);
          message.warning('请检查表单');
        });

      return false;
    },
    // 执行添加
    async handleAdd() {
      // 先进行表单校验

      this.$refs.addForm
        .validate()
        .then(async (result) => {
          // 表单校验成功
          // 第一个表单的数据
          console.log('newEvent', this.newEvent);
          const { enrollRange, eventRange, ...rest } = this.newEvent;
          const postData = {
            ...rest,
          };

          // 报名时间;
          const [enrollStime, enrollEtime] = this.newEvent.enrollRange;
          postData.enrollStime = enrollStime.$d;
          postData.enrollEtime = enrollEtime.$d;

          // 比赛时间
          const [sTime, eTime] = this.newEvent.eventRange;
          postData.stime = sTime.$d;
          postData.etime = eTime.$d;
          postData.jf = JSON.stringify(this.jfList);

          // 添加自定义表单
          postData.cusForm = JSON.stringify(this.cusForm);

          // 开始可以执行ajax要求
          const res = await EventApi.addEvent(postData);

          const { status } = res;
          if (status !== 201) return message.warning('添加失败');
          message.success('添加成功');
          this.showAddModal = false;
          return false;
        })
        .catch((err) => {
          // 表单校验失败
          console.log('err', err);
          message.warning('请检查表单');
        });

      return false;
    },
    async getData() {
      const res = await getBmList({
        keyword: this.eventName,
        $limit: this.limit,
        $page: this.page,
      });
      console.log('res', res);
      const { status, data } = res;
      // 在请求成功得到内容之后 修改表格的数据源
      if (status === 200) {
        this.dataSource = data.data;
        this.total = data.total;
      }
    },
    handleEdit(record) {
      this.curId = record.id; // 标记要修改的信息的id
      this.showEdit = true; // 弹出抽屉
      this.editEvent = _.cloneDeep(record); // 建议使用深拷贝
      this.editEvent.enrollRange = [
        dayjs(this.editEvent.enrollStime),
        dayjs(this.editEvent.enrollEtime),
      ];
      this.editEvent.eventRange = [dayjs(this.editEvent.stime), dayjs(this.editEvent.etime)];
      this.eidtJfList = JSON.parse(this.editEvent.jf);
      console.log('积分奖励列表', this.eidtJfList);
    },

    addRangByCount() {
      this.jfList = [];
      const count = Number(this.rangCount);
      for (let i = 0; i < count; i += 1) {
        this.jfList.push(0);
      }
    },
  },
});
</script>

<style scoped lang="scss">
.mystep {
  margin-bottom: 20px;
}
// 如果需要修改子组件里面的样式 直接书写没有效果的话怎么办？？？？
//   :deep  ::v-deep  /deep/  >>>
:deep .myeditor {
  height: 400px;
}

.it {
  width: 252px;
  display: flex;
}
</style>
